<template>
  <!-- 配件替换件及库存信息 -->
  <div>
    <TopFilter :list="replaceAndInventionTopFilterList" :cols="3" @filterChange="changeHandle" @onCollapse="collapseHandle"></TopFilter>
    <div class="wrap">注：含税采购单价与含税销售单价相等或者含税销售单价与含税参考零售价的价差大于1元，配件行标注为红色提醒。</div>
    <FilterTable
      ref="table"
      columnsRef="part_report_replaceAndInventory"
      :rowstyles="stylesList"
      :columns="columns"
      :datakey="'records'"
      :onColumnsChange="columns => (this.columns = columns)"
      :onSyncTableData="getTableData"
      :dataSource="dataSource"
      :isSelectColumn="false"
      :isMemoryPagination="true"
      :isExportExcel="true"
      :onCalcExportData="exportFun"
      exportFileName="配件替换件及库存信息.xlsx"
    >
      <!-- :fetchapi="fetchApi"
    :params="fetchParams" -->
      <!-- :fetchapi="fetchApi" -->
      <template slot="controls" slot-scope="props">
        <AjaxButton size="small" type="primary" icon="el-icon-add" :disabled="searchBtn" :click="handleSearch">曾查配件号</AjaxButton>
        <!-- <el-button size="small" type="primary" icon="el-icon-daochu" :disabled="exportBtn" @click="handleExport">导出</el-button>
        <el-button size="small" type="primary" icon="el-icon-printer" :disabled="printBtn" @click="handlePrint">打印</el-button> -->
        <!-- <el-button size="small" type="primary" icon="el-icon-plus" @click="publishInfo">新建</el-button>
        <AjaxButton :click="pushDialog" type="primary">发布</AjaxButton>
        <AjaxButton :click="offlineDialog" type="primary">下线</AjaxButton> -->
      </template>
    </FilterTable>
    <BaseDialog :visible.sync="visible" destroyOnClose :title="dialogTitle" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <partNoQuery :partNo="partNoInput" :mode="'single'" :fetchapi="partFetchapi" @close="closeDialog" @onConfirm="confirmHandle" />
    </BaseDialog>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import PartNoQuery from './partNoQuery';
import { getReplaceAndInventoryList, listPartQueryHistory, saveData } from '@/api/part/report/replaceAndInventory';
import { queryPartListByOrderType } from '@/api/part/partPurchase/purchaseOrder';
import { queryPartInfos } from '@/api/part/partInfo';
import moment from 'moment';
export default {
  name: 'ReplaceAndInventory',
  components: { PartNoQuery },
  mixins: [dictionary],
  props: ['partInfo'],
  data() {
    return {
      replaceAndInventionTopFilterList: this.createReplaceAndInventionTopFilterList(),
      columns: this.createTableList(),
      fetchParams: { xhrAbort: true },
      fetchApi: getReplaceAndInventoryList,
      exportBtn: false,
      partFetchapi: queryPartInfos,
      printBtn: false,
      searchBtn: false,
      visible: false,
      dialogTitle: '',
      partHistory: {},
      stylesList: [],
      tableData: [],
      dataSource: this.testDataSource(),
      partNoInput: ''
    };
  },
  computed: {
    savePartNo() {
      return this.replaceAndInventionTopFilterList.find(item => item.fieldName == 'I_MATNR').initialValue;
    }
  },
  mounted() {
    if (this.partInfo && this.partInfo.partNo) {
      this.replaceAndInventionTopFilterList.find(item => item.fieldName == 'I_MATNR').initialValue = this.partInfo.partNo;
      this.partHistory.partNo = this.partInfo.partNo;
      this.partHistory.partName = this.partInfo.partName;
      this.changeHandle({ I_MATNR: this.partInfo.partNo });
    }
  },
  methods: {
    exportFun(row) {
      if (row.referPrice) {
        row.referPrice = Number(row.referPrice * (1 + Number(this.tax))).toFixed(2);
      }
      for (const key in row) {
        // if (!isNaN(row[key])) {

        //   row[key] = Number(row[key]).toFixed(2);
        // }
        switch (key) {
          // 格式化日期
          case 'operateDate':
            // case 'FINISHED_DATE':
            // case 'BALANCE_TIME':
            // case 'SQUARE_DATE':
            if (row[key]) {
              row[key] = moment(row[key]).format('YYYY-MM-DD');
            }
            break;
          // 格式化人名
          case 'CONSULTANT':
            if (row[key]) {
              // row[key] = this.userList[row[key]];
            }
            break;
          // 格式化金额
          case 'COST_TAX_PRICE':
          case 'COST_SALES_PRICE':
          case 'NETWR':
          case 'STOCK_QUANTITY':
          case 'AVAILABLE_QUANTITY':
          case 'YMENG':
          case 'XMENG':
          case 'SMENG':
          case 'AMENG':
          case 'CCKUS':
          case 'BJKUS':
          case 'GZKUS':
          case 'XAKUS':
          case 'JNKUS':
          case 'WHKUS':
          case 'XJKUS':
          case 'DLKUS':
          case 'HDKUS':
            if (row[key]) {
              row[key] = Number(row[key]).toFixed(2);
            }
            break;
          default:
            break;
        }
      }
    },
    testDataSource() {
      return [];
    },
    // 注：含税采购单价与含税销售单价相等或者含税销售单价与含税参考零售价的价差大于1元，配件行标注为红色提醒。
    checkPrice(val) {
      val.forEach(element => {
        // 判断
        if (element.COST_TAX_PRICE == element.COST_SALES_PRICE || Math.abs(element.COST_SALES_PRICE - element.NETWR) > 1) {
          // console.log('不合法数据', element);
          // this.stylesList.push({ row: element, styles: { color: 'red', backgroundColor: '#FBE1E3' } });
          this.stylesList.push({ row: element, styles: { color: 'red' } });
          // this.stylesList = [...this.stylesList];
        }
      });
    },
    // 同步获取表单数据
    async getTableData(val) {
      this.tableData = val;
      this.checkPrice(val);
    },
    // 配件弹窗确定按钮
    confirmHandle(val) {
      this.replaceAndInventionTopFilterList.find(item => item.fieldName == 'I_MATNR').initialValue = val[0].partNo;
      this.partHistory.partNo = val[0].partNo;
      this.partHistory.partName = val[0].partName;
      this.visible = false;
    },
    // 关闭弹窗
    closeDialog() {
      this.visible = false;
    },
    // 点击配件进行搜索
    searchPartsHandle() {
      this.partNoInput = this.replaceAndInventionTopFilterList.find(item => item.fieldName == 'I_MATNR').initialValue;
      // console.log(this.partNoInput,'配件代码');

      this.partFetchapi = queryPartInfos;
      this.dialogTitle = '配件主文件';
      this.visible = true;
    },
    // 曾查配件号
    handleSearch() {
      this.partFetchapi = listPartQueryHistory;
      this.dialogTitle = '曾查配件号';
      this.visible = true;
    },
    // 打印处理
    handlePrint() {},
    // 导出处理
    handleExport() {},
    // 展开收起调用函数
    collapseHandle() {},
    async savePartHistory(val) {
      // 禁用曾查配件
      this.searchBtn = true;
      // console.log(val, '保存参数');
      // this.partHistory.partNo = val.I_MATNR;
      this.partHistory.partNo = this.savePartNo;
      try {
        let res = await saveData(this.partHistory);
      } catch (error) {
      } finally {
        this.searchBtn = false;
      }
    },
    // 搜索条件改变调用方法
    async changeHandle(val) {
      // console.log(val, 123);
      this.$refs.table.START_LOADING();
      this.savePartHistory(val);
      // this.fetchParams = { xhrAbort: false, ImportParameter: val };
      let res = {};
      try {
        res = await getReplaceAndInventoryList({ ImportParameter: val });
      } catch (error) {
      } finally {
        this.searchBtn = false;
        this.$refs.table.STOP_LOADING();
      }
      this.dataSource = [];
      this.dataSource = res.data;
      this.$refs.table.STOP_LOADING();
      // this.columns = [...this.columns];
    },
    // 创建表单字段列表
    createTableList() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        // {
        //   title: '品牌',
        //   dataIndex: 'VTWEG',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input'
        // },
        {
          title: '配件或替换件号',
          dataIndex: 'MATNR',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '配件名称',
          dataIndex: 'PART_NAME',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
          // filterItems: []
        },
        {
          title: '配件说明',
          dataIndex: 'PART_DESCRIPTION',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
          // filterItems: []
        },
        {
          title: '描述',
          dataIndex: 'THJMS',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true
        },
        {
          title: '禁售',
          dataIndex: 'SLFLAG',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '含税采购单价',
          dataIndex: 'COST_TAX_PRICE',
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 2
        },
        {
          title: '含税销售单价',
          dataIndex: 'COST_SALES_PRICE',
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 2
        },
        {
          title: '含税参考零售价',
          dataIndex: 'NETWR',
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 2
        },
        {
          title: '本地库存数量',
          dataIndex: 'STOCK_QUANTITY',
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 2
        },
        {
          title: '本地可用数量',
          dataIndex: 'AVAILABLE_QUANTITY',
          labelWidth: 90,
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 2
        },
        {
          title: '第一点',
          dataIndex: 'DLFLAG',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '第二点',
          dataIndex: 'D2FLAG',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '第三点',
          dataIndex: 'D3FLAG',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '包装信息',
          dataIndex: 'BMENG',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2
        },
        {
          title: 'FIB类别',
          dataIndex: 'MTPOS',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '加价组',
          dataIndex: 'KONDM',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '月已售量',
          dataIndex: 'YMENG',
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 2
        },
        {
          title: '月限售量',
          dataIndex: 'XMENG',
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 2
        },
        {
          title: '安全库存',
          dataIndex: 'SMENG',
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 2
        },
        {
          title: '可用库存',
          dataIndex: 'AMENG',
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 2
        },
        {
          title: '单位',
          dataIndex: 'VRKME',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '长春库库存',
          dataIndex: 'CCKUS',
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 2
        },
        {
          title: '北京库库存',
          dataIndex: 'BJKUS',
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 2
        },
        {
          title: '广州库库存',
          dataIndex: 'GZKUS',
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 2
        },
        {
          title: '西安库库存',
          dataIndex: 'XAKUS',
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 2
        },
        {
          title: '济南库库存',
          dataIndex: 'JNKUS',
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 2
        },
        {
          title: '武汉库库存',
          dataIndex: 'WHKUS',
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 2
        },
        {
          title: '新疆库库存',
          dataIndex: 'XJKUS',
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 2
        },
        {
          title: '成都库库存',
          dataIndex: 'CDKUS',
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 2
        },
        {
          title: '大连库库存',
          dataIndex: 'DLKUS',
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 2
        },
        {
          title: '华东库库存',
          dataIndex: 'HDKUS',
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 2
        }
      ];
    },
    // 创建筛选条件
    createReplaceAndInventionTopFilterList() {
      return [
        {
          type: 'INPUT',
          label: '配件号',
          fieldName: 'I_MATNR',
          placeholder: '',
          rules: [{ required: true, message: '请选择配件号', trigger: 'blur' }],
          unitRender: () => {
            return <el-button slot="append" icon="el-icon-search" onClick={this.searchPartsHandle}></el-button>;
          }
        }
      ];
    }
  }
};
</script>

<style scoped>
.wrap {
  margin-bottom: 15px;
}
</style>
